package zz.demo.springCloud.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import zz.demo.springCloud.config.securityService.SecurityUserService;

/**
 * Created by zhangzheng on 2017-6-21.
 */

//@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
//通过加载此配置可以自定义security的几个默认属性，文档如下：
//An AuthenticationManager bean with in-memory store and a single user (see SecurityProperties.User for the properties of the user).
//Ignored (insecure) paths for common static resource locations (/css/**, /js/**, /images/**, /webjars/** and **/favicon.ico).
//HTTP Basic security for all other endpoints.
//Security events published to Spring’s ApplicationEventPublisher (successful and unsuccessful authentication and access denied).
//Common low-level features (HSTS, XSS, CSRF, caching) provided by Spring Security are on by default.

//oauth2 更多详情请查阅  http://projects.spring.io/spring-security-oauth/docs/oauth2.html
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

//    @Qualifier("sessionRepository")
//    FindByIndexNameSessionRepository<ExpiringSession> sessionRepository;


    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    // 必须给/cloudfoundryapplication/**路径设置为open，以此可以自定义 security configuration和
    // 得到cloud foundry actuator的支持。
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
//                .antMatchers("/oauth/*").permitAll()
                .antMatchers("/info","/static/**","/lib/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
//                .successHandler(new LoginSuccessHandler())
                .and()
            .logout()
                .permitAll()
                .and()
            .httpBasic()
                .and()
//                .invalidateHttpSession(true)
//                .and()
//            .rememberMe()
//                .rememberMeServices(rememberMeServices())
//                .and()
//            .sessionManagement()
//                .maximumSessions(1)
//                .sessionRegistry(sessionRegistry())
        ;
        http.headers().cacheControl();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(securityUserService());
//        auth.inMemoryAuthentication().withUser("zhangsan").password("1").roles("USER");
    }

    //整合spring security和spring session的rememberMe，防止cookie时效出现bug
//    @Bean
//    public RememberMeServices rememberMeServices(){
//        SpringSessionRememberMeServices rememberMeServices=new SpringSessionRememberMeServices();
//        rememberMeServices.setAlwaysRemember(true);
//        rememberMeServices.setValiditySeconds(10 * 60);
//        return rememberMeServices;
//    }

//    @Bean
//    public SpringSessionBackedSessionRegistry sessionRegistry(){
//        return new SpringSessionBackedSessionRegistry(this.sessionRepository);
//    }

   //名字不可为sessionRepository，否则不能正确进入此自定义bean，因为已有sessionRepository的bean注册进了ioc中。
//    @Bean
//    public RedisOperationsSessionRepository sessionRepository(){
//        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
//        jedisConnectionFactory.setPassword("123456");
//        return new SessionRepository();
//    }

//    @Bean
//    public Md5PasswordEncoder passwordEncoder(){
//        return new Md5PasswordEncoder();
//    }

    @Bean
    public SecurityUserService securityUserService(){
        return new SecurityUserService();
    }

}
